package com.company.cloud.product.modules.app.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.art.modules.api.response.Artist;
import com.company.cloud.art.modules.api.service.ArtArtistRemoteService;
import com.company.cloud.behavior.modules.api.response.BehaviorSearchAllModel;
import com.company.cloud.behavior.modules.api.response.BehaviorSearchAllParam;
import com.company.cloud.behavior.modules.api.service.BehaviorClientService;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant.EnabledEnum;
import com.company.cloud.common.constant.BaseConstant.YNEnum;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.common.utils.StrSplitUtils;
import com.company.cloud.company.modules.api.response.CompanySimple;
import com.company.cloud.company.modules.api.service.CompanyRemoteService;
import com.company.cloud.product.modules.api.constant.ProductTypeEnum;
import com.company.cloud.product.modules.api.response.Product;
import com.company.cloud.product.modules.app.controller.req.ProductQuery4PageParam;
import com.company.cloud.product.modules.app.controller.req.ProductRecommendQueryListParam;
import com.company.cloud.product.modules.app.mapper.SaasSitMapMapper;
import com.company.cloud.product.modules.app.service.ProductStockQueryService;
import com.company.cloud.product.modules.base.entity.ProductInfo;
import com.company.cloud.product.modules.base.entity.ProductStockInfo;
import com.company.cloud.product.modules.base.service.ProductInfoService;
import com.company.cloud.product.modules.base.service.ProductStockInfoService;
import com.company.cloud.product.modules.cache.service.ProductInfoCacheService;
import com.company.cloud.product.modules.cache.utils.ProductCacheConvertUtils;
//import com.company.cloud.uba.modules.api.service.UbaLogRemoteService;
import com.company.common.server.config.cloud.ProjectConfig;
import com.company.common.server.constant.IRelBusiType;
import com.company.common.server.log.LogSaasUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;


/**
 * 商品服务
 */
@RestController
@RequestMapping("/app/prd/product")
@Api(tags = "Product_商品信息管理")
public class ProductController {
    @Autowired
    private ProductStockInfoService productStockInfoService;
    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private ProductInfoCacheService productInfoCacheService;

    @Autowired
    private ProductStockQueryService productStockQueryService;

    @Autowired
    private BehaviorClientService behaviorClientService;

//    @Autowired
//    private UbaLogRemoteService ubaLogRemoteService;

    @Autowired
    private CompanyRemoteService companyRemoteService;

    @Autowired
    private ProjectConfig projectConfig;

    @Autowired
    private ArtArtistRemoteService artArtistRemoteService;

    @Autowired
    private SaasSitMapMapper saasSitMapMapper;

    @GetMapping("/sitmap")
    @ApiOperation(value = "sitmap", response = BaseResult.class)
    public BaseResult sitmap() {

        List<String> artist = saasSitMapMapper.artistSitMap();
        List<String> prd = saasSitMapMapper.prdSitMap();
        List<String> news = saasSitMapMapper.newsSitMap();
        List<String> organ = saasSitMapMapper.organSitMap();
        Map<String, List<String>> data = new HashMap<String, List<String>>();
        if (!CollectionUtils.isEmpty(artist)) {
            data.put("artist", artist);
        }
        if (!CollectionUtils.isEmpty(prd)) {
            data.put("prd", prd);
        }
        if (!CollectionUtils.isEmpty(news)) {
            data.put("news", news);
        }
        if (!CollectionUtils.isEmpty(organ)) {
            data.put("organ", organ);
        }
        return BaseResult.ok(data);
    }


    @PostMapping("/query")
    @ApiOperation(value = "商品信息查询", response = Product.class)
    public BaseResult query(@RequestBody ProductQuery4PageParam params) {
        System.out.println("++++++++++++++++++++商品信息查询+++++++++++++++++++++++");
//		if(projectConfig.isCompanyPattern()) { //公司模式
//			LoginSimpleUserInfo userInfo = AuthContextUtils.getUserNoValidate();
//			if(userInfo!=null) {
//				params.setCompanyNo(userInfo.getCompanyNo());
//			}else {
//				params.setCompanyNo(AuthContextUtils.getCompanyNo());
//			}
//		}



        List<String> names = StrSplitUtils.parse2list("caption,orders,price,product_no,brand_id,cost,category_id", String.class);
        String orderName = names.get(RandomUtil.randomInt(0, 7));
        params.setRandom(orderName);
        params.setIsMarketable(YNEnum.YES.getCode());
        try {
            IPage<Product> data = this._query(params);
            return BaseResult.ok(data);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return BaseResult.ok();
    }

    public static void main(String[] args) {

        List<String> names = StrSplitUtils.parse2list("cdt,edt,name,orders,price,product_no", String.class);
        String orderName = names.get(RandomUtil.randomInt(0, 5));
        if(CheckUtils.hasText(orderName)){
            System.out.println("========"+orderName);
        }

        System.out.println(orderName);
    }

    @PostMapping("/getPrdRecommendList")
    @ApiOperation(value = "商品推荐查询", response = Product.class)
    public BaseResult getPrdRecommendList(@RequestBody ProductRecommendQueryListParam params) {

        List<String> names = StrSplitUtils.parse2list("cdt,edt,name,orders,price,product_no", String.class);
        String orderName = names.get(RandomUtil.randomInt(0, 6));

        List<ProductInfo> list = productInfoService.list(
                new QueryWrapper<ProductInfo>()
                        .select("product_no")
                        .eq("rows_state", EnabledEnum.ENABLED.getCode())
                        .eq("is_marketable", YNEnum.YES.getCode())
                        .in("type", Arrays.asList(ProductTypeEnum.Trade_Product.getCode(), ProductTypeEnum.Un_Trade_Product.getCode()))
                        .eq(CheckUtils.hasInt(params.getCategoryId()), "category_id", params.getCategoryId())
                        .eq(CheckUtils.hasText(params.getBizValue10()), "biz_value10", params.getBizValue10())
                        .eq(CheckUtils.hasText(params.getBizValue11()), "biz_value11", params.getBizValue11())
                        .eq(CheckUtils.hasText(params.getBizValue12()), "biz_value12", params.getBizValue12())
                        .orderByDesc(orderName)
                        .last(" limit 0,1000")
        );
        if (list == null || list.size() <= 0) {
            return BaseResult.ok();
        }

        if (params.getNum() <= 0) {
            params.setNum(10);
        }
        Set<String> prdNos = new HashSet<String>();
        if (list.size() <= params.getNum()) {
            list.forEach(item -> {
                prdNos.add(item.getProductNo());
            });
        } else {
            Set<ProductInfo> newSet = RandomUtil.randomEleSet(list, params.getNum());
            newSet.forEach(item -> {
                prdNos.add(item.getProductNo());
            });
        }

        ProductQuery4PageParam queryParams = new ProductQuery4PageParam();
        queryParams.setProductNos(prdNos);
        queryParams.setRows(params.getNum() + 1);
        IPage<Product> data = this._query(queryParams);
        return BaseResult.ok(data.getRecords());
    }


    private boolean hasText(String val, String eqVal) {
        boolean flag = CheckUtils.hasText(val);
        if (flag == false) {
            return false;
        }
        if (val.equals(eqVal)) {
            return true;
        } else {
            return false;
        }
    }


    public IPage<Product> _query(ProductQuery4PageParam params) {

        String tag = null;
        if (StringUtils.hasText(params.getTagId())) {
            tag = StrUtil.format(",{},", params.getTagId());
        }

        String subCategoryId = null;
        if (StringUtils.hasText(params.getSubCategoryId())) {
            subCategoryId = StrUtil.format(",{},", params.getSubCategoryId());
        }

        IPage<ProductInfo> page = productInfoService.page(new Page<>(params.getPage(), params.getRows()),
                new QueryWrapper<ProductInfo>().eq("rows_state", EnabledEnum.ENABLED.getCode())
                        .eq(StringUtils.hasText(params.getCompanyNo()), "company_no", params.getCompanyNo())
                        .eq(StringUtils.hasText(params.getIsMarketable()), "is_marketable", params.getIsMarketable())
                        .eq(CheckUtils.hasInt(params.getCategoryId()), "category_id", params.getCategoryId())
                        .eq(CheckUtils.hasText(params.getProductNo()), "product_no", params.getProductNo())
                        .in(CollUtil.isNotEmpty(params.getProductNos()), "product_no", params.getProductNos())
                        .like(CheckUtils.hasText(params.getName()), "name", params.getName())
                        .like(CheckUtils.hasText(params.getCaption()), "caption", params.getCaption())
                        .like(CheckUtils.hasText(params.getKeyword()), "keyword", params.getKeyword())
                        .eq(CheckUtils.hasText(params.getType()), "type", params.getType())
                        .eq(CheckUtils.hasText(params.getTwoType()), "two_type", params.getTwoType())
                        .eq(CheckUtils.hasInt(params.getBrandId()), "brand_id", params.getBrandId())
                        .like(StringUtils.hasText(tag), "tag_values", tag)
                        .like(StringUtils.hasText(subCategoryId), "tree_path", subCategoryId)
                        .eq(CheckUtils.hasText(params.getBizValue1()), "biz_value1", params.getBizValue1())
                        .eq(CheckUtils.hasText(params.getBizValue2()), "biz_value2", params.getBizValue2())
                        .eq(CheckUtils.hasText(params.getBizValue3()), "biz_value3", params.getBizValue3())
                        .eq(CheckUtils.hasText(params.getBizValue4()), "biz_value4", params.getBizValue4())
                        .eq(CheckUtils.hasText(params.getBizValue7()), "biz_value7", params.getBizValue7())
                        .eq(CheckUtils.hasText(params.getBizValue8()), "biz_value8", params.getBizValue8())
                        .eq(CheckUtils.hasText(params.getBizValue9()), "biz_value9", params.getBizValue9())

                        .eq(CheckUtils.hasText(params.getBizValue10()), "biz_value10", params.getBizValue10())
                        .eq(CheckUtils.hasText(params.getBizValue11()), "biz_value11", params.getBizValue11())
                        .eq(CheckUtils.hasText(params.getBizValue12()), "biz_value12", params.getBizValue12())
                        .eq(CheckUtils.hasText(params.getBizValue13()), "biz_value13", params.getBizValue13())
                        .eq(CheckUtils.hasText(params.getBizValue14()), "biz_value14", params.getBizValue14())
                        .eq(CheckUtils.hasText(params.getBizValue15()), "biz_value15", params.getBizValue15())
                        .eq(CheckUtils.hasText(params.getBizValue16()), "biz_value16", params.getBizValue16())
                        .eq(CheckUtils.hasText(params.getBizValue17()), "biz_value17", params.getBizValue17())
                        .eq(CheckUtils.hasText(params.getBizValue18()), "biz_value18", params.getBizValue18())
                        .like(CheckUtils.hasText(params.getBizValue19()), "biz_value19", params.getBizValue19())
                        .like(CheckUtils.hasText(params.getBizValue20()), "biz_value20", params.getBizValue20())

                        .ge(CheckUtils.hasBigDecimal(params.getPriceGe()), "price", params.getPriceGe())
                        .le(CheckUtils.hasBigDecimal(params.getPriceLe()), "price", params.getPriceLe())

                        .ge(CheckUtils.hasText(params.getBizValue5Ge()), "biz_value5", params.getBizValue5Ge())
                        .le(CheckUtils.hasText(params.getBizValue5Le()), "biz_value5", params.getBizValue5Le())

                        .ge(CheckUtils.hasText(params.getBizValue6Ge()), "biz_value6", params.getBizValue6Ge())
                        .le(CheckUtils.hasText(params.getBizValue6Le()), "biz_value6", params.getBizValue6Le())

                        .orderByAsc(this.hasText(params.getOrderByPrice(), "asc"), "price")
                        .orderByDesc(this.hasText(params.getOrderByPrice(), "desc"), "price")

                        .orderByAsc(this.hasText(params.getOrderByDate(), "asc"), "edt")
                        .orderByDesc(this.hasText(params.getOrderByDate(), "desc"), "edt")
                        .orderByDesc(CheckUtils.hasText(params.getRandom()), params.getRandom())

                       

                        .orderByDesc((CheckUtils.isEmpty(params.getOrderByDate()) && CheckUtils.isEmpty(params.getOrderByPrice())), "orders")


        );

        if (page == null || CollectionUtils.isEmpty(page.getRecords())) {
            return null;
        }
        Set<String> productNos = new HashSet<String>();
        Set<String> artistNos = new HashSet<String>();
        page.getRecords().forEach(item -> {
            productNos.add(item.getMainProductNo());
            if (StrUtil.isNotEmpty(item.getBizValue4())) {
                Set<String> artistNos2 = StrSplitUtils.parse2set(item.getBizValue4(), String.class);
                artistNos.addAll(artistNos2);
            }
        });

        Map<String, ProductStockInfo> stockMap = productStockQueryService.getPrdStockByPrd(productNos);

        BaseClientResult<Map<String, CompanySimple>> companyResp = companyRemoteService.getCompanyMapSimple(productNos);
        Map<String, CompanySimple> companyMap = companyResp.getData();

        //作家
        BaseClientResult<Map<String, Artist>> artistResp = artArtistRemoteService.artistInfoMap(artistNos);
        Map<String, Artist> artistData = BaseClientResult.getResultData(artistResp, new HashMap<String, Artist>());

        IPage<Product> data = page.convert(new Function<ProductInfo, Product>() {
            @Override
            public Product apply(ProductInfo entity) {
                Product product = ProductCacheConvertUtils.convertProduct(entity, null, null);
                ProductStockInfo stock = stockMap.get(product.getMainProductNo());
                if (stock != null) {
                    product.setStockNum(stock.getNum());
                    product.setFreezeNum(stock.getFreezeNum());
                }
                if (!CollectionUtils.isEmpty(companyMap)) {
                    CompanySimple companySimple = companyMap.get(product.getCompanyNo());
                    if (companySimple != null) {
                        product.setCompanyName(companySimple.getName());
                        product.setCompanyLogo(companySimple.getLogo());
                        product.setCompanyType(companySimple.getType());
                    }
                }

                if (StrUtil.isNotEmpty(entity.getBizValue4())) {
                    Set<String> artistNos3 = StrSplitUtils.parse2set(entity.getBizValue4(), String.class);
                    if (artistNos3.size() > 0) {
                        for (String ano : artistNos3) {
                            Artist artist = artistData.get(ano);
                            if (artist != null) {
                                product.addArtist(ProductCacheConvertUtils.getArtist(artist));
                                product.addArtistName(artist.getName());
                            }
                        }
                    }
                }
                return product;
            }
        });

        return data;
    }

    @GetMapping("/getSQL")
    @ApiOperation(value = "getSQL", response = BaseResult.class)
    public BaseResult getSQL() {

        System.out.println("------update 1");
        saasSitMapMapper.dynamicsUpdate("UPDATE prd_product_info set orders=1 where orders<=1000000");

        System.out.println("------update 2");
        saasSitMapMapper.dynamicsUpdate(" UPDATE prd_product_info a, ( "
                + "SELECT rel_id ,count(1) as n from uba_user_browse_obj_log where rel_id_type ='50'  "
                + "GROUP BY rel_id ) b set a.orders=b.n where a.product_no=b.rel_id");

        return BaseResult.ok();
    }


    @GetMapping("/get")
    @ApiOperation(value = "商品", response = Product.class)
    public BaseResult get(@RequestParam("productNo") String productNo) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUserNoValidate();
        Product product = productInfoCacheService.getProductByNoByCache(productNo);
        //库存
        Set<String> productNos = new HashSet<String>();
        productNos.add(product.getMainProductNo());
        Map<String, ProductStockInfo> stockMap = productStockQueryService.getPrdStockByPrd(productNos);
        ProductStockInfo stock = stockMap.get(product.getMainProductNo());
        if (stock != null) {
            product.setStockNum(stock.getNum());
            product.setFreezeNum(stock.getFreezeNum());
            product.getSkuItems().forEach(m->{
                final ProductStockInfo stockInfo = productStockInfoService.getOne(new QueryWrapper<ProductStockInfo>().eq("product_no", m.getProductNo()).eq("sku_no", m.getSkuNo()));
                System.out.println("========stockInfo========="+stockInfo);
                if(stockInfo!=null){
                    m.setStockNum(stockInfo.getNum());
                    m.setFreezeNum(stockInfo.getFreezeNum());
                }
                System.out.println("==========m=================="+m);
            });
        }


        //公司信息
        BaseClientResult<CompanySimple> companyResp = companyRemoteService.getCompanySimple(product.getCompanyNo());
        if (CheckUtils.hasClientResult(companyResp)) {
            product.setCompany(companyResp.getData());
        }

        //关注信息
        BehaviorSearchAllParam behaviorParam = new BehaviorSearchAllParam();
        behaviorParam.setObjType(IRelBusiType.PRD_Product);
        behaviorParam.setObjNo(productNo);
        behaviorParam.setUserTop(5);
        behaviorParam.setCollectionFlg(true);
        behaviorParam.setFollowFlg(true);
        behaviorParam.setThumbsUpFlg(true);
        behaviorParam.setUserId(userInfo == null ? null : userInfo.getId());
        BaseClientResult<BehaviorSearchAllModel> behaviorResp = behaviorClientService.getBehaviorInfo(behaviorParam);
        product.setBehavior(BaseClientResult.getResultData(behaviorResp));

        //作家
        if (StrUtil.isNotEmpty(product.getBizValue4())) {
            Set<String> artistNos = StrSplitUtils.parse2set(product.getBizValue4(), String.class);
            if (artistNos.size() > 0) {
                BaseClientResult<List<Artist>> artistResp = artArtistRemoteService.artistInfoList(artistNos);
                List<Artist> artistData = BaseClientResult.getResultData(artistResp, new ArrayList<Artist>());
                artistData.forEach(item -> {
                    product.addArtist(ProductCacheConvertUtils.getArtist(item));
                    product.addArtistName(item.getName());
                });
            }
        }

        return BaseResult.ok(product);
    }

}
